package com.empire.module.member.controller.admin.transportationrecord;

import com.empire.framework.common.exception.util.ServiceExceptionUtil;
import com.empire.module.member.enums.ErrorCodeConstants;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.io.IOException;

import com.empire.framework.common.pojo.PageParam;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.common.pojo.CommonResult;
import com.empire.framework.common.util.object.BeanUtils;
import static com.empire.framework.common.pojo.CommonResult.success;

import com.empire.framework.excel.core.util.ExcelUtils;

import com.empire.framework.apilog.core.annotation.ApiAccessLog;
import static com.empire.framework.apilog.core.enums.OperateTypeEnum.*;

import com.empire.module.member.controller.admin.transportationrecord.vo.*;
import com.empire.module.member.dal.dataobject.transportationrecord.TransportationRecordDO;
import com.empire.module.member.service.transportationrecord.TransportationRecordService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 交通记录")
@RestController
@RequestMapping("/member/transportation-record")
@Validated
public class TransportationRecordController {

    @Resource
    private TransportationRecordService transportationRecordService;

    @PostMapping("/create")
    @Operation(summary = "创建交通记录")
    @PreAuthorize("@ss.hasPermission('member:transportation-record:create')")
    public CommonResult<Long> createTransportationRecord(@Valid @RequestBody TransportationRecordSaveReqVO createReqVO) {
        return success(transportationRecordService.createTransportationRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新交通记录")
    @PreAuthorize("@ss.hasPermission('member:transportation-record:update')")
    public CommonResult<Boolean> updateTransportationRecord(@Valid @RequestBody TransportationRecordSaveReqVO updateReqVO) {
        transportationRecordService.updateTransportationRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除交通记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('member:transportation-record:delete')")
    public CommonResult<Boolean> deleteTransportationRecord(@RequestParam("id") Long id) {
        transportationRecordService.deleteTransportationRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得交通记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('member:transportation-record:query')")
    public CommonResult<TransportationRecordRespVO> getTransportationRecord(@RequestParam("id") Long id) {
        TransportationRecordDO transportationRecord = transportationRecordService.getTransportationRecord(id);
        return success(BeanUtils.toBean(transportationRecord, TransportationRecordRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得交通记录分页")
//    @PreAuthorize("@ss.hasPermission('member:transportation-record:query')")
    public CommonResult<PageResult<TransportationRecordRespVO>> getTransportationRecordPage(@Valid TransportationRecordPageReqVO pageReqVO) {
        PageResult<TransportationRecordDO> pageResult = transportationRecordService.getTransportationRecordPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, TransportationRecordRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出交通记录 Excel")
    @PreAuthorize("@ss.hasPermission('member:transportation-record:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTransportationRecordExcel(@Valid TransportationRecordPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TransportationRecordDO> list = transportationRecordService.getTransportationRecordPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "交通记录.xls", "数据", TransportationRecordRespVO.class,
                        BeanUtils.toBean(list, TransportationRecordRespVO.class));
    }

    @GetMapping("/export-word/{presentationId}")
    @Operation(summary = "下载出行报告")
    public void exportWord(@PathVariable("presentationId") Long presentationId,
                           @RequestParam("fileName") String fileName,
                           HttpServletResponse response) {
        try {
            // 处理文件名编码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
                    .replaceAll("\\+", "%20");

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
            response.setHeader("Cache-Control", "no-cache"); // 禁止缓存，避免数据不全

            // 调用服务层写入文件流
            transportationRecordService.exportTransportationRecords(presentationId, fileName, response.getOutputStream());

            // 刷新输出流
            response.flushBuffer();
        } catch (Exception e) {
            // 异常处理（可以通过全局异常处理器统一处理）
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.PRESENTATION_FILE_DOWNLOAD_FAIL, e.getMessage());
        }
    }

}